import * as THREE from 'three';
import { init } from './logic.js'; // 引入初始化函数
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';

class SceneManager {
  constructor() {
    this.scene = new THREE.Scene();
    this.camera = new THREE.PerspectiveCamera(
      75,
      window.innerWidth / window.innerHeight,
      0.1,
      1000
    );
    this.camera.position.set( 2.1, 2, 3.1);
    this.renderer = new THREE.WebGLRenderer({
      antialias: true,
    });
    this.renderer.setSize(window.innerWidth, window.innerHeight);
    const canvas = document.getElementById('renderCanvas');
    canvas.appendChild(this.renderer.domElement);
    //设置场景背景色为灰色
    this.scene.background = new THREE.Color(0xcccccc);

    this.controls = new OrbitControls(this.camera, this.renderer.domElement);
    this.controls.enableDamping = true;
    this.controls.dampingFactor = 0.05;
    this.controls.target.set(-0.3, 0.8,  -0.3);
    this.controls.update();

    this.addLights();
  
  }
  addLights() {
    // 柔和的环境光
    const ambientLight = new THREE.AmbientLight(0xffffff, 0.6);
    this.scene.add(ambientLight);

    // 主光源（模拟太阳）
    const mainLight = new THREE.DirectionalLight(0xffffff, 1.2);
    mainLight.position.set(5, 10, 7);
    mainLight.castShadow = true;
    mainLight.shadow.bias = -0.0001;
    mainLight.shadow.mapSize.width = 1024;
    mainLight.shadow.mapSize.height = 1024;
    this.scene.add(mainLight);

    // 辅助光源（柔和阴影）
    const fillLight = new THREE.DirectionalLight(0xffffff, 0.4);
    fillLight.position.set(-5, 5, -7);
    fillLight.castShadow = false;
    this.scene.add(fillLight);

    // 顶部微弱光
    const topLight = new THREE.DirectionalLight(0xffffff, 0.2);
    topLight.position.set(0, 20, 0);
    topLight.castShadow = false;
    this.scene.add(topLight);
  }

  addFloor() {
    const floorGeometry = new THREE.PlaneGeometry(10, 10);
    const floorMaterial = new THREE.MeshStandardMaterial({ color: 0x888888 });
    const floor = new THREE.Mesh(floorGeometry, floorMaterial);
    floor.rotation.x = -Math.PI / 2;
    this.scene.add(floor);
  }

  animate() {
    const animateLoop = () => {
      requestAnimationFrame(animateLoop);
      this.controls.update();
      this.renderer.render(this.scene, this.camera);
    };
    animateLoop();
  }

  onResize() {
    window.addEventListener('resize', () => {
      this.camera.aspect = window.innerWidth / window.innerHeight;
      this.camera.updateProjectionMatrix();
      this.renderer.setSize(window.innerWidth, window.innerHeight);
    });
  }
}

// 使用 SceneManager
const sceneManager = new SceneManager();
window.sceneManager = sceneManager; // 方便在浏览器控制台访问
sceneManager.animate();
sceneManager.onResize();
init(sceneManager.scene);

window.sceneManager2 = function() {
console.log('Camera Position:', window.sceneManager.camera.position);
//获取相机朝向
console.log('Camera LookAt:', window.sceneManager.camera.getWorldDirection(new THREE.Vector3()));
}